#include "thememanager.h"

#include <QFile>
#include <QApplication>
#include <QByteArray>
#include <QSettings>
#include <QtDebug>

ThemeManager::ThemeManager( QDir themesDir, const QString & defaultName, QObject * parent ) : QObject( parent ) {
    this->mActiveTheme = "";
    this->mDirectory = themesDir;
    this->loadThemes();

    this->restoreTheme( defaultName ); // restore previous theme or use default if not found
}

ThemeManager::~ThemeManager() {
    this->saveTheme(); // save theme on application closing
}

// set active theme
// will replace application stylesheet
void ThemeManager::select( const QString & name ) {
    if ( name == this->mActiveTheme || name.isEmpty() ) {
        return; // asked to load previous stylesheet, do nothing
    }

    QString content = this->styleSheetContent( name );

    if ( !content.isEmpty() ) { // check if we got content
        // let qt handle stylesheet
        qApp->setStyleSheet( content );

        // keep active theme name in memory
        this->mActiveTheme = name;
    }
}

QString ThemeManager::styleSheetContent( QString name ) {
    // open file for reading
    QFile file( this->mDirectory.absoluteFilePath( name + ".css" ) );
    if ( !file.open( QIODevice::ReadOnly | QIODevice::Text ) ) { // check if file exists
        qDebug() << "Requested theme does not exist or did not install css file on folder.";
        return "";
    }

    // return all content
    return QString( file.readAll() );
}

void ThemeManager::loadThemes() {
    foreach ( QString fileName, this->mDirectory.entryList( QDir::Files ) ) {
        if ( fileName.endsWith( ".css" ) ) { // themes are a .css file for now
            this->mThemes.append( fileName.left( fileName.lastIndexOf( "." ) ) ); // keep filename without .css extension
        }
    }
}

void ThemeManager::restoreTheme( const QString & defaultTheme ) {
    QSettings settings;
    QString themeName = settings.value( "theme", defaultTheme ).toString();
    this->select( themeName );
}

void ThemeManager::saveTheme() {
    QSettings settings;
    settings.setValue( "theme", this->mActiveTheme );
}

QStringList ThemeManager::themes() {
    return this->mThemes;
}

const QString & ThemeManager::activeTheme() {
    return this->mActiveTheme;
}
